package com.zx._03_并发.chapter_07_limit;

import com.google.common.util.concurrent.RateLimiter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @version v1.0
 * @Project: knowledge
 * @Title: LimitTest
 * @Description: 使用令牌桶算法进行限流
 * @author: zhangxue
 * @date: 2018年12月8日下午9:44:15
 * @company: 未知之地
 * @Copyright: Copyright (c) 2018
 */
public class LimitTest2 {

    private final static ExecutorService pool = Executors.newCachedThreadPool();

    private final static RateLimiter limiter = RateLimiter.create(1);//令牌桶的容量为5。每秒中向容器中放入5个令牌

    private final static LimitTest2 test = new LimitTest2();

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            pool.execute(() -> {
                double acquire = limiter.acquire();
                System.out.println("获取令牌成功!,消耗=" + acquire);
                test.get();
            });
        }
    }

    public void get() {
        System.out.println(Thread.currentThread().getName());
    }
}
